#include "state_manager.h"
#include "elog.h"
#include "elog_file.h"
#include "ws_response.h"
#include "dwarf_utils.h"

StateManager* StateManager::pinstance_ = nullptr;
std::mutex StateManager::singleton_mutex_;


StateManager::StateManager() {
    cam_tele_ = CamTele();
    cam_wide_ = CamWide();
    system_ = System();
    rgb_power_ = RgbPower();
    panorama_ = Dwarf2Panorama();
}

StateManager::~StateManager() {

}

StateManager* StateManager::GetInstance() {
    std::lock_guard<std::mutex> lock(singleton_mutex_);
    if (pinstance_ == nullptr) {
        pinstance_ = new StateManager();
    }
    return pinstance_;
}


bool StateManager::getCamTeleState() {
    return cam_tele_.getCameraState();
}

CamTelePhotoState StateManager::getCamTelePhotoState() {
    return cam_tele_.getPhotoState();
}

CamTeleTimelapseState StateManager::getCamTeleTimelapseState() {
    return cam_tele_.getTimelapseState();
}

CamWidePhotoState StateManager::getCamWidePhotoState() {
    return cam_wide_.getPhotoState();
}

int StateManager::checkEle() {
    int cur_ele = rgb_power_.getEle();

    log_i("checkEle global ele = %d", cur_ele);
    wsCommonResWithInt(CMD_NOTIFY_ELE, MODULE_NOTIFY, CMD_TYPE_NOTIFICATION, cur_ele, 0);

    if (cur_ele < 8) {
        if (cam_tele_.getTimelapseState() == CAM_TIMELAPSE_RECORDING)
            cam_tele_.stopTimeLapsePhotograph();
        
        if (cam_tele_.getRecordState() == CAM_RECORDING)
            cam_tele_.stopRecord();

        if (astro_.getCaptureLightState() == STATE_RUNNING)
            astro_.stopCaptureRawLiveStacking();

        if (astro_.getCaptureDarkState() == STATE_RUNNING)
            astro_.stopCaptureDark();
    }

    return 0;
}

int StateManager::checkCloseCamera() {
    log_i("checkCloseCamera");
    long cur_timestamp = getTimestampInSeconds();

    if (cam_tele_.getPhotoState() != CAM_TELE_PHOTO_IDLE) {
        return 0;
    }

    if (cam_tele_.getRecordState() != CAM_RECORD_IDLE) {
        return 0;
    }

    if (cam_tele_.getPanoramaState() == CAM_PANORAMA_PHOTOGRAPHING) {
        return 0;
    }

    if (cam_tele_.getTimelapseState() == CAM_TIMELAPSE_RECORDING) {
        return 0;
    }

    if (cam_wide_.getPhotoState() != CAM_WIDE_PHOTO_IDLE) {
        return 0;
    }

    if (cam_wide_.getTimelapseState() == CAM_WIDE_TIMELAPSE_RECORDING) {
        return 0;
    }

    if (astro_.getAstroState() != STATE_IDLE)
        return 0;

    if (focus_.isFocusStateIdle() != STATE_IDLE) {
        return 0;
    }

    if (tracker_.getTrackState() != STATE_IDLE) {
        return 0;
    }

    if (cur_timestamp - getWsClientTimelapse() > 600) {
        updateWsClientTimlapse();
        cam_tele_.closeCamera();
        cam_wide_.closeCamera();
    }

    return 0;
}